package com.infoblazer.jimql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;

/**
 *
 * User: Dave
 * Date: Nov 18, 2010
 * Time: 10:30:38 PM
 *
 */
public class HsqlJimql implements JimqlConnection{
    public Connection buildConnection(ThreadLocal<Connection> connectionThreadLocal){
        Connection conn = null;
        Random random = new Random();
        String dbName =String.valueOf(Math.abs(random.nextInt()));
        try {
            conn = connectionThreadLocal.get();
            if (conn==null){
             conn = DriverManager.getConnection("jdbc:hsqldb:mem:"+dbName, "jimql", "");
             connectionThreadLocal.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
          return conn;
    }

    
    public void dropIfExists(Connection conn ,String tableName) throws SQLException {

         Statement st = null;
         try {
             st = conn.createStatement();
            StringBuilder sb = new StringBuilder();
            sb.append("DROP TABLE ").append(tableName).append(" IF EXISTS");
            st.execute(sb.toString());
            } catch (SQLException ok) {

            }
        finally {
             st.close();
         }

    }
}
